import axios, { type AxiosRequestConfig, type AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import pinia from "@/stores";


const reqeust = axios.create({
  baseURL: import.meta.env.VITE_APP_API,
  timeout: 5000,
});

// 添加请求拦截器
reqeust.interceptors.request.use(function (config: AxiosRequestConfig) {
  // 在发送请求之前做些什么
  const store = useUserStore(pinia)
  config.headers!.Authorization = "Bearer " + store.token;
  return config;
});

// 添加响应拦截器
reqeust.interceptors.response.use(
  function (response: AxiosResponse) {
    // 对响应数据做点什么
    return response.data.data;
  },
  function (error) {
    ElMessage.error(error.response.data.message);
    console.clear();
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default reqeust;
